package com.common.web;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.RequestWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.model.AdminUser;
import com.common.model.BaseUser;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.common.model.TimePlan;
import com.common.servcie.CommonService;
import com.teacher.service.TeacherService;
import com.teacher.util.DateUtils;

/**
 * 公用的控制器
 * 例如登陆功能
 * @author yww
 *
 */
@Controller
@RequestMapping(value="/")
public class CommonController {
	@Autowired
	private CommonService service;
	@Autowired
	private TeacherService tservice;
	private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
	/**
	 * 显示登陆页面
	 * @return
	 */
	@RequestMapping(value="/showLogin",method=RequestMethod.GET)
	public ModelAndView showLoginPage(HttpSession session){
		// 登陆过的用户进入此页面不再重复登陆
		ModelAndView mav=new ModelAndView();
		BaseUser user=(BaseUser) session.getAttribute("user");
		if(user!=null){
			if(user.getUserType()==null){
				user.setUserType("student");
			}
			switch (user.getUserType()) {
			case "admin":
				mav.setViewName("redirect:/admin/profile");
				break;
			case "teacher":
				mav.setViewName("redirect:/teacher/teacher_home");
				break;
			case "student":
				mav.setViewName("redirect:/student/info");
				break;
			default:
				session.removeAttribute("user");
				mav.setViewName("common/error");
				mav.addObject("error","登陆错误");
				break;
			}
		}else{
			mav.setViewName("common/login");
		}
		return mav;
	}
	/**
	 * 用于实现用户登陆功能
	 * @param no 用户登陆账号
	 * @param password  用户登陆密码
	 * @return 成功返回1,2,3 分别对应为学生，教师，管理员。错误返回-1，-2 ,-3分别对应账号不存在，密码错误,信息不完整
	 */
	@ResponseBody
	@RequestMapping("/login")
	public int login(@RequestParam(required=true) String no,@RequestParam(required=true)String password,HttpSession session){
		//去掉登陆信息
		session.removeAttribute("user");
		logger.info(no+" is logining");
		if(no.trim().isEmpty()||password.trim().isEmpty()){
			logger.info("login failed,no or password is empty");
			return -3;
		}
		switch (service.getUserType(no.trim())) {
		//学生登陆
		case "student":
			logger.info("user type is student");
			StudentUser student=service.studentLogin(no, password);
			if(student==null){
				logger.info("login failed,wrong password");
				return -2;
			}
			session.setAttribute("user", student);
			logger.info("login succeed");
			return 1;
			//教师登陆
		case "teacher":
			logger.info("user type is teacher");
			TeacherUser teacher=service.teacherLogin(no, password);
			
			if(teacher==null){
				logger.info("login failed,wrong password");
				return -2;
			}
			TimePlan tp = tservice.getTimePlanByTeacherId(teacher.getId());
			teacher.setEnableUpdate(DateUtils.CompareDate(tp.getTeacherEditTimeStart(), tp.getTeacherEditTimeEnd()));
			long  days = DateUtils.between_Days(tp.getTeacherChooseTimeStart(), new Date());
			double eachTimeLength = tp.getTeacherChooseEachTimeLength();
			double tmp = days/eachTimeLength;
			long ltmp = (long)tmp;
			days = tmp>ltmp?ltmp+1:ltmp;
			teacher.setMaxLevel(days);
			//设置能否评阅题目
			teacher.setEnableAuth(DateUtils.CompareDate(tp.getMiddleCheckTimeStart(), tp.getMiddleCheckTimeEnd()));
			//设置能否上传任务书
			teacher.setEnableUploadTaskFile(DateUtils.CompareDate(tp.getTeacherUploadTimeStart(), tp.getTeacherUploadTimeEnd()));
			//计算能否选择学生
			Date endtime = DateUtils.dateAdd(tp.getTeacherChooseTimeStart(), (int)(tp.getTotalLevelCount()*tp.getTeacherChooseEachTimeLength()), Calendar.DAY_OF_MONTH);
//			System.out.println(endtime.toLocaleString());
			teacher.setEnableChooseStudent(DateUtils.CompareDate(tp.getTeacherChooseTimeStart(), endtime));
			//设置是否处于中期检查状态
			teacher.setEnableMiddleCheck(DateUtils.CompareDate(tp.getMiddleCheckTimeStart(), tp.getMiddleCheckTimeEnd()));
			teacher.setSelectWays(tp.getChooseByProject());
			teacher.setEnableFinalCheck(DateUtils.CompareDate(tp.getFinalCheckTimeStart(), tp.getFinalCheckTimeEnd()));
			teacher.setAfterFinalCheck(tp.getFinalCheckTimeEnd().before(new Date()));
			System.out.println(teacher.getAfterFinalCheck());
			System.out.println(tp.getFinalCheckTimeEnd());
			System.out.println(new Date().toLocaleString());
			session.setAttribute("user", teacher);
			logger.info("login succeed");
			return 2;
			//管理员登陆
		case "admin":
			logger.info("user type is admin");
			AdminUser admin=service.adminLogin(no, password);
			if(admin==null){
				logger.info("login failed,wrong password");
				return -2;
			}
			session.setAttribute("user", admin);
			logger.info("login succeed");
			return 3;
		default:
			logger.info("login failed,no such user with no"+no);
			return -1;
		}
	}
	
	
	
	/**
	 * 退出登陆处理
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView  LogOut(HttpServletRequest request)
	{
		request.getSession().removeAttribute("user");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("redirect:/showLogin");
		
		return mav;
	}
}
